﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DrugStorehouseMIS.BLL;
using DrugStorehouseMIS.Comm;

namespace DrugStorehouseMIS.StockInAndOutManager
{
    public partial class frmStockIn : Form
    {

        private GridPrinter gridPrinter;
        private StockInHeader stockInHeaderBLL;
        private StockInDetail stockInDetailBLL;
        private StockInType stockInTypeBLL;
        private Manager managerBLL;

        public frmStockIn()
        {
            InitializeComponent();

            stockInHeaderBLL = new StockInHeader();
            stockInDetailBLL = new StockInDetail();
            stockInTypeBLL = new StockInType();

            stockInHeaderBLL.StockInTypeName = new StockInType();
            stockInHeaderBLL.SupplierName = new Supplier();
            stockInDetailBLL.DrugNum = new Drug();

            managerBLL = new Manager();
        }

        private void frmStockIn_Load(object sender, EventArgs e)
        {
            BindStockInType();
            LoadDataGridViewHeader();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tabStockIn_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabStockIn.SelectedTab.Text == "入库单明细")
            {
                LoadDataGridViewDetail();
            }
            else if(tabStockIn.SelectedTab.Text=="入库单汇总")
            {
                LoadDataGridViewHeader();
            }
        }


        private void printDocumentHeader_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            bool more = gridPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }

        #region 入库单汇总

        /// <summary>
        /// 绑定入库类型
        /// </summary>
        public void BindStockInType()
        {
            IList<StockInType> list = stockInTypeBLL.GetAllStockInType();
            foreach (StockInType obj in list)
            {
                cbxFliterStockInType.Items.Add(obj.StockInTypeName);
            }
           //cbxFliterStockInType.SelectedIndex = 0;
        }

        /// <summary>
        /// 根据入库单状态设置能否编辑、查询、审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdbNoApproval_CheckedChanged(object sender, EventArgs e)
        {
            LoadDataGridViewHeader();
            if (rdbNoApproval.Checked == true && dgvStockInHeader.Rows.Count>0)
            {
                tsBtnInHeaderConfirm.Enabled = tsBtnInHeaderDelete.Enabled = tsBtnInHeaderEdit.Enabled = true;
            }
            else
            {
                tsBtnInHeaderConfirm.Enabled = tsBtnInHeaderDelete.Enabled = tsBtnInHeaderEdit.Enabled = false;
            }
        }

        /// <summary>
        /// 多条件加载header信息
        /// </summary>
        public void LoadDataGridViewHeader()
        {
            dgvStockInHeader.DataSource = stockInHeaderBLL.Fliter(txtFilterStockInNum.Text.Trim(), cbxFliterStockInType.Text, txtFilterSupplier.Text.Trim(), GetStatus());
            //dgvStockInHeader.DataSource = stockInHeaderBLL.DisplayByStatus(GetStatus());
            if (dgvStockInHeader.Rows.Count > 0 && GetStatus() == "未审核")
            {
                tsBtnInHeaderEdit.Enabled = true;
                tsBtnInHeaderDelete.Enabled = true;
                tsBtnInHeaderConfirm.Enabled = true;
            }
            else
            {
                tsBtnInHeaderConfirm.Enabled = false;
                tsBtnInHeaderDelete.Enabled = false;
                tsBtnInHeaderEdit.Enabled = false;
            }

            Tool.ResetAllTextBox(gbInHeaderInfo);
            rtbInfoInHeaderRemark.Text = "";
        }

        /// <summary>
        /// 获取选中状态
        /// </summary>
        /// <returns></returns>
        public string GetStatus()
        {
            if (rdbNoApproval.Checked == true)
            {
                return rdbNoApproval.Text;
            }
            else
            {
                return rdbAlreadyApproval.Text;
            }
        }

        /// <summary>
        /// 获取选中行的对象
        /// </summary>
        /// <returns></returns>
        public StockInHeader GetHeaderRowObject()
        {
            StockInHeader header = new StockInHeader();
            header.StockInTypeName = new StockInType();
            header.SupplierName = new Supplier();
            if (dgvStockInHeader.CurrentRow.Index >= 0)
            {
                header.ApprovalBy = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["ApprovalBy"].Value.ToString();
                header.CreatedBy = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["CreatedBy"].Value.ToString();
                header.Remark = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["Remark"].Value.ToString();
                header.Status = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["Status"].Value.ToString();
                header.StockInDatetime = Convert.ToDateTime(dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["StockInDate"].Value);
                header.StockInNum = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["HeaderStockInNum"].Value.ToString();
                header.StockInTypeName.StockInTypeName = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["StockInType"].Value.ToString();
                header.SupplierName.SupplierName = dgvStockInHeader.Rows[dgvStockInHeader.CurrentRow.Index].Cells["Supplier"].Value.ToString();
            }

            return header;
        }

        /// <summary>
        /// 设置header打印的相关信息
        /// </summary>
        /// <returns></returns>
        private bool InitHeaderPrinting()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != DialogResult.OK)
            {
                return false;
            }
            printDocument.DocumentName = "入库汇总单";
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.DefaultPageSettings = printDialog.PrinterSettings.DefaultPageSettings;
            printDocument.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(40, 40, 40, 40);
            gridPrinter = new GridPrinter(dgvStockInHeader, printDocument, true, true, "入库汇总单", new Font("黑体", 24, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);


            return true;
        }

        /// <summary>
        /// 新建入库单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInHeaderNew_Click(object sender, EventArgs e)
        {
            frmStockInHeaderNew form = new frmStockInHeaderNew();
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewHeader();
            }
        }

        /// <summary>
        /// 编辑入库单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInHeaderEdit_Click(object sender, EventArgs e)
        {               
            frmStockInHeaderEdit form = new frmStockInHeaderEdit();
            form.Init(GetHeaderRowObject());
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewHeader();
            }     
        }

        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInHeaderDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                stockInHeaderBLL.RemoveStockInHeader(GetHeaderRowObject().StockInNum);//已通过存储过程里删除对应的detail
                LoadDataGridViewHeader();
            }    
        }

        /// <summary>
        /// 审核后的各种药品的入库数量等信息放到库存表里
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInHeaderConfirm_Click(object sender, EventArgs e)
        {
            StockInHeader header = new StockInHeader();
            header.StockInTypeName = new StockInType();
            header.SupplierName = new Supplier();
            IList<StockInDetail> list = new List<StockInDetail>();
            header = this.GetHeaderRowObject();
            list = stockInDetailBLL.GetStockInDetailAll(header.StockInNum);
            DialogResult result = MessageBox.Show("确定审核吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                header.Status = "已审核";
                header.ApprovalBy = frmMain.userObject.UserName; //获取登录用户
                stockInHeaderBLL.SetStockInHeader(header);     //更新状态

                managerBLL.ConfirmStockIn(header, list);
                LoadDataGridViewHeader();
            }
        }
  
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInHeaderPrint_Click(object sender, EventArgs e)
        {
            if (InitHeaderPrinting()) 
            { 
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog(); 
                printPreviewDialog.Document = printDocument; 
                printPreviewDialog.ShowDialog();
            } 
            
        }    

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInHeaderSearch_Click(object sender, EventArgs e)
        {
            LoadDataGridViewHeader();
        }

        /// <summary>
        /// 重置查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInHeaderReset_Click(object sender, EventArgs e)
        {
            cbxFliterStockInType.SelectedIndex = 0;
            txtFilterStockInNum.Text = "";
            txtFilterSupplier.Text = "";
        }

        /// <summary>
        /// 单击单元格将相应信息显示在textbox中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvStockInHeader_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1) //防止点击列标题栏报错
            {
                txtInfoInHeaderNum.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["HeaderStockInNum"].Value.ToString();
                txtInfoInHeaderType.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["StockInType"].Value.ToString();
                txtInfoInHeaderDate.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["StockInDate"].Value.ToString();
                txtInfoInHeaderSupplier.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["Supplier"].Value.ToString();
                txtInfoInHeaderCreatedBy.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["CreatedBy"].Value.ToString();
                txtInfoInHeaderApprovalBy.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["ApprovalBy"].Value.ToString();
                rtbInfoInHeaderRemark.Text = dgvStockInHeader.Rows[e.RowIndex].Cells["Remark"].Value.ToString();
            }
        }

        #endregion

        #region 入库单明细

        /// <summary>
        /// 
        /// </summary>
        public void LoadDataGridViewDetail()
        {
            if (dgvStockInHeader.Rows.Count > 0)
            {
                StockInHeader header = this.GetHeaderRowObject();
                dgvStockInDetail.DataSource = stockInDetailBLL.GetStockInDeatilByNum(header.StockInNum);
                if (header.Status == "已审核" || dgvStockInDetail.Rows.Count < 0)
                {
                    tsBtnInDetailDelete.Enabled = false;
                    tsBtnInDetailEdit.Enabled = false;
                }
            }
            else
            {
                tsBtnInDetailDelete.Enabled = false;
                tsBtnInDetailEdit.Enabled = false;
            }

            Tool.ResetAllTextBox(gbxInDetailInfo);

        }

        /// <summary>
        /// 获取选中的行，再构建成一个对象
        /// </summary>
        /// <returns></returns>
        public StockInDetail GetDetailRowObject()
        {
            StockInDetail detail = new StockInDetail();
            detail.DrugNum = new Drug();

            detail.Amount = Convert.ToSingle(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["Amount"].Value);
            detail.BatchNum = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["BatchNum"].Value.ToString();
            detail.DrugNum.DrugNum = Convert.ToInt32(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["DrugNum"].Value);
            detail.ExpiryDatetime = Convert.ToDateTime(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["ExpiryDate"].Value);
            detail.ImportPrice = Convert.ToSingle(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["ImportPrice"].Value);
            detail.ProductedArea = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["ProductedArea"].Value.ToString();
            detail.ProductedDatetime = Convert.ToDateTime(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["ProductedDate"].Value);
            detail.Quantity = Convert.ToInt32(dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["Quantity"].Value);
            detail.StockInNum = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["StockInNum"].Value.ToString();

            return detail;
        }

        /// <summary>
        /// 设置detail打印的相关信息
        /// </summary>
        /// <returns></returns>
        private bool InitDetailPrinting()
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != DialogResult.OK)
            {
                return false;
            }
            printDocument.DocumentName = "入库明细单";
            printDocument.PrinterSettings = printDialog.PrinterSettings;
            printDocument.DefaultPageSettings = printDialog.PrinterSettings.DefaultPageSettings;
            printDocument.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(40, 40, 40, 40);
            gridPrinter = new GridPrinter(dgvStockInDetail, printDocument, true, true, "入库明细单", new Font("黑体", 24, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);


            return true;
        }

        /// <summary>
        /// 新建一条明细记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInDetailNew_Click(object sender, EventArgs e)
        {
            StockInHeader obj = this.GetHeaderRowObject();
            frmStockInDetailNew form = new frmStockInDetailNew();
            form.Init(obj);
            form.ShowDialog();
            if (form.DialogResult == DialogResult.OK)
            {
                LoadDataGridViewDetail();
            }
        }

        /// <summary>
        /// 编辑入库明细单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInDetailEdit_Click(object sender, EventArgs e)
        {
            if (dgvStockInDetail.Rows.Count > 0)
            {
                StockInHeader header= this.GetHeaderRowObject();
                StockInDetail detail = this.GetDetailRowObject();
                frmStockInDetailEdit form = new frmStockInDetailEdit();
                string aDrugName = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["TradeName"].Value.ToString();
                string aSepcifications = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["Specifications"].Value.ToString();
                string aMeasuringUnit=dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["MeasuringUnit"].Value.ToString();
                string aTradePrice=dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["TradePrice"].Value.ToString();
                string aRetailPrice = dgvStockInDetail.Rows[dgvStockInDetail.CurrentRow.Index].Cells["RetailPrice"].Value.ToString();

                form.Init(header, detail, aDrugName, aSepcifications, aMeasuringUnit, aTradePrice, aRetailPrice);
                form.ShowDialog();
                if (form.DialogResult == DialogResult.OK)
                {
                    LoadDataGridViewDetail();
                }
            }

        }

        /// <summary>
        /// 根据单号和药品号删除明细单的某一记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInDetailDelete_Click(object sender, EventArgs e)
        {
             DialogResult result = MessageBox.Show("确定删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
             if (result == DialogResult.OK)
             {
                 StockInDetail detail = this.GetDetailRowObject();
                 stockInDetailBLL.RemoveStockInDetail(detail.StockInNum, detail.DrugNum.DrugNum);
                 LoadDataGridViewDetail();
             }
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnInDetailPrint_Click(object sender, EventArgs e)
        {
            if (InitDetailPrinting())
            {
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.Document = printDocument;
                printPreviewDialog.ShowDialog();
            } 
        }

        /// <summary>
        /// 单击单元格将相应信息显示在textbox中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvStockInDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)   //防止点击列标题栏报错
            {
                txtInfoInStockInNum.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["StockInNum"].Value.ToString(); 
                txtInfoInDrugName.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["TradeName"].Value.ToString();
                txtInfoInSpecifications.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["Specifications"].Value.ToString();
                txtInfoInUnit.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["MeasuringUnit"].Value.ToString();
                txtInfoInProductedArea.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["ProductedArea"].Value.ToString();
                txtInfoInBatchNum.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["BatchNum"].Value.ToString();
                txtInfoInProductedDate.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["ProductedDate"].Value.ToString();
                txtInfoInExpiryDate.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["ExpiryDate"].Value.ToString();
                txtInfoInTradePrice.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["TradePrice"].Value.ToString();
                txtInfoInRetailPrice.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["RetailPrice"].Value.ToString();
                txtInfoInImportPrice.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["ImportPrice"].Value.ToString();
                txtInfoInQutntity.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(); ;
                txtInfoInAmount.Text = dgvStockInDetail.Rows[e.RowIndex].Cells["Amount"].Value.ToString();                           
            }
        }

        #endregion
     
        # region 查询

        private void txtFilterStockInNum_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadDataGridViewHeader();
            }
        }

        private void txtFilterSupplier_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadDataGridViewHeader();
            }
        }

        private void cbxFliterStockInType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataGridViewHeader();
        }

        #endregion          
    }
}